package com.library.dao;

import com.library.entity.Admin;
import com.library.util.C3p0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.SQLException;

public class AdminDao {
    private final QueryRunner queryRunner = new QueryRunner(C3p0Utils.getDataSource());

    /**
     * 通过id查询信息
     *
     * @param id 管理员id
     * @return
     */
    public Admin getById(Integer id) {
        String sql = "select * from admin where id = ?";
        Admin admin = null;
        try {
            admin = queryRunner.query(sql, new ScalarHandler<Admin>(), id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return admin;
    }

    public String getPasswordByUsername(String username) {
        String sql = "SELECT password FROM admin WHERE username = ?";
        try {
            return queryRunner.query(sql, new ScalarHandler<String>(), username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Admin getByUsername(String username) {
        String sql = "SELECT * FROM admin WHERE username = ?";
        try {
            return queryRunner.query(sql, new org.apache.commons.dbutils.handlers.BeanHandler<>(Admin.class), username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
